package com.atguigu.filter;

import com.atguigu.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author YAO
 * @create 2021-05-13 20:37
 */
public class ManagerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        User user = (User) httpServletRequest.getSession().getAttribute("user");
        //如果用户属性为空，说明没登录
        if(user == null){
            httpServletRequest.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);
        }else if(!"admin".equals(user.getUsername())){
            //不是管理员，跳到主页
            httpServletRequest.getRequestDispatcher("/index.jsp").forward(request,response);
        }else {
            //不为空，则放行
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
